package shin.blog.web.logic;

import java.util.List;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import shin.test.web.logic.PMF;

public class DbControllerBase<T> implements IDbControllerBase<T>{

	protected Class<T> tClass ;
	
	protected final Log logger = LogFactory.getLog(getClass());
	
	private static final PersistenceManagerFactory pmfInstance =
        JDOHelper.getPersistenceManagerFactory("transactions-optional");
	
    public static PersistenceManagerFactory getPMF() {
        return pmfInstance;
    }
    
	@Override
	public T delete(Long id) {
		T t = get(id);
		return delete(t);
	}

	@Override
	public T delete(T t) {
		PersistenceManager pm = getPMF().getPersistenceManager();
	    pm.setDetachAllOnCommit(true);
	    try {
	    	pm.deletePersistent(t);
	    } finally {
	        pm.close();
	    }
		return t;
	}

	@Override
	public T get(Long id) {
		PersistenceManager pm = getPMF().getPersistenceManager();
	    pm.setDetachAllOnCommit(true);
	    T e;
	    try {
	        e = pm.getObjectById(tClass,id);
	    } finally {
	        pm.close();
	    }
	   
		return e;
	}

	
	@SuppressWarnings("unchecked")
	@Override
	public List<T> gets() {
		PersistenceManager pm = getPMF().getPersistenceManager();
		String query = "select from " + tClass.getName();
        List<T> lists = (List<T>) pm.newQuery(query).execute();
		return lists;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> gets(String query) {
		PersistenceManager pm = getPMF().getPersistenceManager();
        List<T> lists = (List<T>) pm.newQuery(query).execute();
		return lists;
	}

	@Override
	public T save(T t) {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            pm.makePersistent(t);
        } finally {
            pm.close();
        }
        return t;
	}

	@Override
	public T update(T t) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            pm.makePersistent(t);
        } finally {
            pm.close();
        }
        return t;
	}
}
